package com.api.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.LongSerializationPolicy;

public final class DataUtil {

	private DataUtil() {
	}

	public static <T> T getDtoForClass(Class<?> aClass, Type returnType) {
		InputStream resource = aClass.getResourceAsStream(aClass.getSimpleName() + ".json");
		return getDto(resource, returnType);
	}

	public static <T> T getDto(Reader reader, Type returnType) {
		try {
			BufferedReader bufferedReader = new BufferedReader(reader);
			return readFromJSon(bufferedReader, returnType);
		} catch (Exception e) {

			throw new IllegalStateException(String.format("Couln't parse json to class '%s'", returnType), e);
		}
	}

	public static <T> T getDto(InputStream inputStream, Type returnType) {
		if (inputStream == null) {
			throw new IllegalArgumentException("InputStream cannot be null");
		}
		InputStreamReader in = new InputStreamReader(inputStream);
		return getDto(in, returnType);
	}

	public static <T> T getDtoFromJSon(String json, Type returnType) {
		return getDto(new StringReader(json), returnType);
	}

	private static <T> T readFromJSon(Reader reader, Type returnType) {
		GsonBuilder gs = new GsonBuilder();
		gs.serializeNulls();
		gs.disableHtmlEscaping();
		gs.setLongSerializationPolicy(LongSerializationPolicy.STRING);

		Gson gson = gs.create();
		@SuppressWarnings("unchecked")
		T result = (T) gson.fromJson(reader, returnType);
		return result;
	}
}
